package com.wendy.thirdpartyaccess.qq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wendy.model.QQUserInfo;
import com.wendy.thirdpartyaccess.SocialConstants;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhuwending
 */
@Slf4j
public class QQAuthenticationManager implements AuthenticationManager {


    private static final List<GrantedAuthority> AUTHORITIES = new ArrayList<>(16);

    static {
        AUTHORITIES.add(new SimpleGrantedAuthority("admin"));
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (authentication.getName() != null && authentication.getCredentials() != null) {
            QQUserInfo userInfo = getUserInfo(authentication.getName(), String.valueOf(authentication.getCredentials()));
            return new UsernamePasswordAuthenticationToken(userInfo, null, AUTHORITIES);
        }
        return null;
    }

    private QQUserInfo getUserInfo(String accessToken, String openId) {
        String url = String.format(SocialConstants.USER_INFO_API, SocialConstants.USER_INFO_URL, accessToken, SocialConstants.CLIENT_ID, openId);
        Document document;
        try {
            document = Jsoup.connect(url).get();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            throw new BadCredentialsException("Bad Credentials!");
        }
        String resultText = document.text();
        JSONObject json = JSON.parseObject(resultText);
        QQUserInfo userInfo = new QQUserInfo();
        userInfo.setNickname(json.getString("nickname"));
        userInfo.setGender(json.getString("gender"));
        userInfo.setProvince(json.getString("province"));
        userInfo.setYear(json.getString("year"));
        userInfo.setAvatar(json.getString("figureurl_qq_2"));
        return userInfo;
    }
}
